<?php

class UsersActions extends Actions {

  public function pageDefault(){
    $this->authenticate();
    $this->administratorsOnly();
    $this->redirect(Config::get('base_url', "/")."users/list");
  }

  public function pageList(){
    $this->authenticate();
    $this->administratorsOnly();
    $csrf = Session::get('csrf');
    if(empty($csrf)) {
        $csrf = md5(rand(1, 1000) . microtime());
        Session::set('csrf', $csrf);
    }
    
    $users = new Usuario();
    
    $view = new View("listado");    
    $view->data->users = $users->listPage(array('page' => $this->param('page')));
    $lastPage = $users->lastPage();
    $page = max(min($lastPage, $this->param('page')), 1);
    $view->data->page = $page;
    $view->data->lastPage = $lastPage;
    $view->data->csrfToken = $csrf;
    $view->show();
  }
  
  public function pageCreate(){
    $this->authenticate();
    $this->administratorsOnly();
    
    $error = array();
    $r = $this->param('r');
    
    if(is_array($r)){
      if(empty($r['name'])) $error['name'] = "Indique un nombre.";
      if(empty($r['email'])) $error['email'] = "Indique un correo electrónico.";
      if(empty($r['password'])) $error['password2'] = "No deje en blanco la contraseña.";
      if($r['password'] != $r['password2']) $error['password2'] = "Las claves indicadas no coinciden.";
      
      $image = $this->saveImage();
      if(!empty($image)) $r['lab_image'] = $image;
      
      //trato de guardar el registro
      if(empty($error)){
        try {
          Usuario::create($r);
          $this->redirect(Config::get('base_url', "/")."users/list/page_".$this->param('page'));
        } catch(Exception $e) {
          $error['_general'] = "No se pudo guardar el usuario.";
        }
      }
    }

    $view = new View("crearEditar");
    $view->data->user = is_array($r)?$r:array();
    $view->data->error = $error;
    $view->data->creating = true;
    $view->show();
    
  }

  public function pageEdit(){
    $this->authenticate();
    $this->administratorsOnly();
    
    $error = array();
    $r = $this->param('r');
    
    if(is_array($r)){
        //Inspect::view($r); die();
      if(empty($r['name'])) $error['name'] = "Indique un nombre.";
      if(empty($r['email'])) $error['email'] = "Indique un correo electrónico.";
      if($r['password'] != $r['password2']) $error['password2'] = "Las claves indicadas no coinciden.";
      
      //editor y administrator son checkboxes.  Si no existen es porque no estaban chequeados.
      $r['editor'] = empty($r['editor'])? 0 : 1 ;
      $r['administrator'] = empty($r['administrator'])? 0 : 1 ;
      
      $image = $this->saveImage();
      if(!empty($image)) $r['lab_image'] = $image;
      
      //trato de guardar el registro
      if(empty($error)){
        try {
          $user = new Usuario();
          if($r['password'] == '') {
            unset($r['password']);
            unset($r['password2']);
          }
          $user->data($r);
          $user->save();
          $this->redirect(Config::get('base_url', "/")."users/list/page_".$this->param('page'));
        } catch(Exception $e) {
          $error['_general'] = "No se pudo guardar el usuario.";
        }
      }
    } else {
      $r = Usuario::find($this->param('id'))->data();
      unset($r['password']);
    }

    $view = new View("crearEditar");
    $view->data->user = is_array($r)?$r:array();
    $view->data->error = $error;
    $view->data->creating = false;
    $view->show();
  }
  
  public function pageDelete(){
    $this->authenticate();
    $this->administratorsOnly();
    
    $csrf = Session::get('csrf');
    if($csrf != $this->param('token')) $this->redirect(Config::get('base_url', "/")."error/404");
    
    $users = new Usuario();
    
    $users->delete(array('id' => $this->param("id")));
    
    $this->redirect(Config::get('base_url', "/")."users/list/page_".$this->param('page'));
  }
  
  protected function administratorsOnly(){
    if(!User::getInstance()->dataItem('administrator')) {
        header("HTTP/1.0 404 Not Found");
        header("Status: 404 Not Found");
        $this->redirect(Config::get('base_url', "/").'error/404');
    }
  }
  
  private function saveImage(){
    if(isset($_FILES) && isset($_FILES['imagen']) && !empty($_FILES['imagen']['name'])){
      $imagen = !empty($_FILES['imagen']['name'])?substr(md5(microtime(1)),0,6)."_".basename($_FILES['imagen']['name']):false;
      move_uploaded_file($_FILES['imagen']['tmp_name'], Config::get('public_path', '/').'/fotos_labs/'.$imagen);
      return $imagen;
    }
    return false;
  }
}